package cn.xiaolang.function.delay_queue;

import org.junit.Test;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StopWatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO
 *
 * @author fuhw/DeanKano
 * @date 2019-03-19 09:53
 */
public class QueueTest {



    @Test
    public void testExecutors() throws InterruptedException {
//        Thread.sleep(10000);

        ExecutorService e = Executors.newFixedThreadPool(24);
        StopWatch t = new StopWatch();
        t.start();

        CountDownLatch c = new CountDownLatch(5000);
        for (int i = 0; i < 5000; i++) {
            e.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":do..");
                    try {
                        c.countDown();
                        Thread.sleep(200);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            });
        }
        c.await();
        t.stop();
        System.out.println(t.prettyPrint());
    }

    @Test
    public void testThreadPool() throws InterruptedException {
//        Thread.sleep(10000);


        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(24);
        threadPool.setMaxPoolSize(24);
//        threadPool.setQueueCapacity(100);
        threadPool.setWaitForTasksToCompleteOnShutdown(Boolean.TRUE);
        threadPool.setKeepAliveSeconds(60);
        threadPool.initialize();

        StopWatch t = new StopWatch();
        t.start();
        CountDownLatch c = new CountDownLatch(5000);

        for (int i = 0; i < 5000; i++) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + ":do..");
                        c.countDown();
                        Thread.sleep(200);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            });
        }
        c.await();
        t.stop();
        System.out.println(t.prettyPrint());
    }
}
